package com.atguigu.lease.web.admin.custom.interceptor;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.login.LoginUser;
import com.atguigu.lease.common.login.LoginUserHolder;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

// 拦截器
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// 获取token
		String token = request.getHeader("access-token");

		Claims claims = JwtUtil.parseToken(token);
		System.out.println("claims = " + claims);
		Long userId = claims.get("userId",Long.class);
		String username = claims.get("username",String.class);
		// ThreadLocal 用于在多线程环境中为每个线程提供独立的变量副本。
		// 每个线程都可以独立地访问和修改其自己的变量副本，而不会影响其他线程中的副本。
		// 将userId和username set进threadLocal（线程本地）中
		LoginUserHolder.setLoginUser(new LoginUser(userId, username));

		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		LoginUserHolder.clear();
	}
}
